package prototype.deepclone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import lombok.NoArgsConstructor;

/**
 * @author DFD
 * @date 2023年11月14日
 */
@NoArgsConstructor
public class DeepProtoType implements Serializable, Cloneable {

	private static final long serialVersionUID = 4311988580279915115L;

	public String name; // String 属性
	public DeepCloneableTarget deepCloneableTarget;// 引用类型

	/**
	 * 深拷贝 - 方式 1 使用clone 方法
	 */
	@Override
	protected DeepProtoType clone() throws CloneNotSupportedException {
		// 先对基本属性的克隆
		DeepProtoType deepProtoType = (DeepProtoType) super.clone();
		// 再对引用类型克隆
		deepProtoType.deepCloneableTarget = deepCloneableTarget.clone();
		return deepProtoType;
	}

	/**
	 * 方式 2 采用对象的序列化实现 (推荐)
	 * @return
	 */
	protected DeepProtoType streamClone() {
		DeepProtoType copyObj = null;
		ByteArrayOutputStream bos = null;
		ByteArrayInputStream bis = null;
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		try {
			bos = new ByteArrayOutputStream();
			// 序列化
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);// 当前这个对象以对象流的方式输出
			// 反序列化
			bis = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bis);
			copyObj = (DeepProtoType) ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
				oos.close();
				bis.close();
				ois.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

		return copyObj;
	}
}
